import axios from 'axios';

// 创建axios实例
const instance = axios.create({
  baseURL: '/api',
  timeout: 60000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
instance.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    // 如果响应状态码是401，则可能是未认证或token过期
    if (error.response && error.response.status === 401) {
      localStorage.removeItem('token');
      // 可以在这里添加重定向到登录页面的逻辑
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

// API方法
const api = {
  // 认证相关
  login: (username, password) => {
    return instance.post('/login', { username, password });
  },
  
  verifyToken: () => {
    return instance.get('/verify-token');
  },
  
  // 数据处理相关
  uploadData: (formData) => {
    return instance.post('/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  },
  
  // ICA分析相关
  trainICA: (params) => {
    return instance.post('/train/ica', params);
  },
  
  getICAContribution: () => {
    return instance.get('/analysis/ica/contribution');
  },
  
  getICADiagnosis: () => {
    return instance.get('/analysis/ica/diagnosis');
  },
  
  // AE分析相关
  trainAE: (params) => {
    return instance.post('/train/ae', params);
  },
  
  // PCA分析相关
  trainPCA: (params) => {
    return instance.post('/train/pca', params);
  },
  
  // PLS分析相关
  trainPLS: (params) => {
    return instance.post('/train/pls', params);
  }
};

export default api; 